package com.maxima.maximaAttendance.actions;

import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.maxima.maximaAttendance.daos.AdminDAO;
import com.opensymphony.xwork2.ActionSupport;

public class AdminLogin extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = 1L;
	private String username;
	private String password;
	private Map<String, Object> map;

	@Override
	public void setSession(Map<String, Object> map) {
		this.map = map;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public String execute() throws Exception {
		Object obj = this.map.get("firstLogin");
		if (obj != null) {
			if ((Boolean) obj == true) {
				return SUCCESS;
			} else {
				return ERROR;
			}
		} else {
			return ERROR;
		}
	}

	public String firstLogin() {
		setUsername(ServletActionContext.getRequest().getParameter("username"));
		setPassword(ServletActionContext.getRequest().getParameter("password"));
		if (new AdminDAO().checkLogin(this.username, this.password)) {
			map.put("usersList", new UserList().initUserList());
			map.put("firstLogin", true);
			this.setSession(map);
			return SUCCESS;
		}
		return ERROR;
	}

	public String secondLogin() {
		Object obj = this.map.get("adminLogin");
		if (obj != null) {
			if ((Boolean) obj == true) {
				return SUCCESS;
			} else {
				return check();
			}
		} else {
			return check();
		}
	}

	public String check() {
		this.username = ServletActionContext.getRequest().getParameter(
				"username");
		this.password = ServletActionContext.getRequest().getParameter(
				"password");
		if (this.username != null && this.password != null)
			if (this.username.equals("Administrator"))
				if (new AdminDAO().checkLogin(this.username, this.password)) {
					map.put("adminLogin", true);
					this.setSession(map);
					return SUCCESS;
				} else {
					return ERROR;
				}
		return ERROR;
	}

	public String logout() {
		map.put("firstLogin", false);
		map.put("usersList", null);
		this.setSession(map);
		return SUCCESS;
	}
	public String adminLogout() {
		map.put("adminLogin", false);
		map.put("usersList", new UserList().initUserList());
		this.setSession(map);
		return SUCCESS;
	}
}
